import 'package:flutter_test/flutter_test.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:lmmi/common/index.dart';

void main() {
  group('Username Update Fix Tests', () {
    setUpAll(() async {
      // 初始化Hive（内存模式用于测试）
      Hive.init('test');

      // 注册适配器
      if (!Hive.isAdapterRegistered(0)) {
        Hive.registerAdapter(UserEntityAdapter());
      }
      if (!Hive.isAdapterRegistered(1)) {
        Hive.registerAdapter(ShareEntityAdapter());
      }

      // 初始化服务
      await UserService.initialize();
    });

    tearDownAll(() async {
      await Hive.deleteFromDisk();
    });

    setUp(() async {
      // 清理测试数据
      final userBox = Hive.box<UserEntity>('users');
      final currentUserBox = Hive.box('current_user');
      await userBox.clear();
      await currentUserBox.clear();
    });

    test('should remove old user record when username is updated', () async {
      // 创建测试用户
      final originalUser = UserEntity(
        id: 'test_user_123',
        username: 'original_username',
        password: 'password123',
        avatar: 'test_avatar.jpg',
        share: ['share1', 'share2'],
        isVip: true,
        like: ['like1'],
      );

      // 保存原始用户
      final success1 = await UserService.updateUser(originalUser);
      expect(success1, isTrue);

      // 验证原始用户存在
      final box = Hive.box<UserEntity>('users');
      expect(box.containsKey('original_username'), isTrue);
      expect(box.get('original_username')?.id, equals('test_user_123'));

      // 模拟登录该用户（设置为当前用户）
      await box.put('original_username', originalUser);
      final currentUserBox = Hive.box('current_user');
      await currentUserBox.put('user', originalUser.toJson());

      // 更新用户名
      final updatedUser = originalUser.copyWith(username: 'new_username');
      final success2 = await UserService.updateUser(updatedUser);
      expect(success2, isTrue);

      // 验证新用户名存在
      expect(box.containsKey('new_username'), isTrue);
      final newUser = box.get('new_username');
      expect(newUser?.id, equals('test_user_123'));
      expect(newUser?.username, equals('new_username'));
      expect(newUser?.password, equals('password123'));
      expect(newUser?.share, equals(['share1', 'share2']));
      expect(newUser?.isVip, isTrue);
      expect(newUser?.like, equals(['like1']));

      // 验证旧用户名记录已被删除
      expect(box.containsKey('original_username'), isFalse);

      // 验证当前用户信息也已更新
      final currentUser = UserService.getCurrentUser();
      expect(currentUser?.username, equals('new_username'));
      expect(currentUser?.id, equals('test_user_123'));
    });

    test('should handle username update for non-current user', () async {
      // 创建两个测试用户
      final user1 = UserEntity(
        id: 'user_1',
        username: 'user1_original',
        password: 'password1',
        avatar: 'avatar1.jpg',
        share: [],
        isVip: false,
        like: [],
      );

      final user2 = UserEntity(
        id: 'user_2',
        username: 'user2_original',
        password: 'password2',
        avatar: 'avatar2.jpg',
        share: [],
        isVip: false,
        like: [],
      );

      // 保存两个用户
      await UserService.updateUser(user1);
      await UserService.updateUser(user2);

      // 设置user1为当前用户
      final currentUserBox = Hive.box('current_user');
      await currentUserBox.put('user', user1.toJson());

      // 更新user2的用户名（非当前用户）
      final updatedUser2 = user2.copyWith(username: 'user2_new');
      final success = await UserService.updateUser(updatedUser2);
      expect(success, isTrue);

      final box = Hive.box<UserEntity>('users');

      // 验证user2的新用户名存在
      expect(box.containsKey('user2_new'), isTrue);
      expect(box.get('user2_new')?.id, equals('user_2'));

      // 验证user2的旧用户名记录已被删除
      expect(box.containsKey('user2_original'), isFalse);

      // 验证user1没有受到影响
      expect(box.containsKey('user1_original'), isTrue);
      expect(box.get('user1_original')?.id, equals('user_1'));

      // 验证当前用户仍然是user1
      final currentUser = UserService.getCurrentUser();
      expect(currentUser?.id, equals('user_1'));
      expect(currentUser?.username, equals('user1_original'));
    });

    test('should not delete anything when username is not changed', () async {
      // 创建测试用户
      final user = UserEntity(
        id: 'test_user_456',
        username: 'unchanged_username',
        password: 'password123',
        avatar: 'old_avatar.jpg',
        share: [],
        isVip: false,
        like: [],
      );

      // 保存用户
      await UserService.updateUser(user);

      // 设置为当前用户
      final currentUserBox = Hive.box('current_user');
      await currentUserBox.put('user', user.toJson());

      final box = Hive.box<UserEntity>('users');
      final initialUserCount = box.length;

      // 更新用户信息但不改变用户名（只改变头像）
      final updatedUser = user.copyWith(avatar: 'new_avatar.jpg');
      final success = await UserService.updateUser(updatedUser);
      expect(success, isTrue);

      // 验证用户数量没有变化
      expect(box.length, equals(initialUserCount));

      // 验证用户名仍然存在
      expect(box.containsKey('unchanged_username'), isTrue);

      // 验证头像已更新
      final retrievedUser = box.get('unchanged_username');
      expect(retrievedUser?.avatar, equals('new_avatar.jpg'));
      expect(retrievedUser?.id, equals('test_user_456'));
    });

    test('should prevent duplicate usernames after update', () async {
      // 创建两个用户
      final user1 = UserEntity(
        id: 'user_1',
        username: 'user1',
        password: 'password1',
        avatar: 'avatar1.jpg',
        share: [],
        isVip: false,
        like: [],
      );

      final user2 = UserEntity(
        id: 'user_2',
        username: 'user2',
        password: 'password2',
        avatar: 'avatar2.jpg',
        share: [],
        isVip: false,
        like: [],
      );

      await UserService.updateUser(user1);
      await UserService.updateUser(user2);

      // 验证用户名检查功能
      expect(UserService.isUsernameExists('user1'), isTrue);
      expect(UserService.isUsernameExists('user2'), isTrue);
      expect(UserService.isUsernameExists('nonexistent'), isFalse);

      // 尝试将user2的用户名改为user1（应该被阻止）
      // 这个测试验证了设置页面中的用户名检查逻辑
      final wouldConflict =
          UserService.isUsernameExists('user1') && 'user1' != user2.username;
      expect(wouldConflict, isTrue);
    });
  });
}
